package main

import (
	"context"
	"log"
	"time"

	"go.etcd.io/etcd/api/v3/mvccpb"
	clientv3 "go.etcd.io/etcd/client/v3"
)

func main() {
	cli, err := clientv3.New(clientv3.Config{
		Endpoints:   []string{"localhost:2379"},
		DialTimeout: 5 * time.Second,
	})
	if err != nil {
		log.Fatal(err)
	}
	defer cli.Close()
	go func() {
		for {
			cli.Put(context.TODO(), "/cron/jobs/job3", "job3")
			cli.Delete(context.TODO(), "/cron/jobs/job3")
			time.Sleep(1 * time.Second)
		}
	}()
	getResp, err := cli.Get(context.TODO(), "/cron/jobs/job3")
	if err != nil {
		log.Fatal(err)
	}
	if len(getResp.Kvs) != 0 {
		log.Println("当前", string(getResp.Kvs[0].Value))
	}
	ctx, cancelFunc := context.WithCancel(context.TODO())
	time.AfterFunc(5*time.Second, func() {
		cancelFunc()
	})
	for watchResp := range cli.Watch(ctx, "/cron/jobs/job3", clientv3.WithRev(getResp.Header.Revision+1)) {
		for _, event := range watchResp.Events {
			switch event.Type {
			case mvccpb.PUT:
				log.Println("修改为", string(event.Kv.Value), event.Kv.CreateRevision, event.Kv.ModRevision)
			case mvccpb.DELETE:
				log.Println("删除了", event.Kv.ModRevision)
			}
		}
	}
}
